package de.klenkse.eclipse.ftpsync.synchronizer;

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;

/**
 * Removes a resource.
 */
public class ResourceRemoveCommand extends ResourceCommand {
	/**
	 * The resource.
	 */
	private IResource resource;
	/**
	 * The remote path.
	 */
	private String remotePath;

	/**
	 * The constructor.
	 */
	public ResourceRemoveCommand(IResource resource, String remoteRelPath) {
		this.resource = resource;
		this.remotePath = remoteRelPath;
	}

	/** {@inheritDoc} */
	@Override
	public String toString() {
		return "Removing " + resource.toString() + " from " + remotePath;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @throws IOException
	 */
	@Override
	public void execute(FTPClient client) throws IOException {
		if (resource instanceof IFolder) {
			recursiveRemoveFolder(client, remotePath);
			client.removeDirectory(remotePath);
		} else if (resource instanceof IFile) {
			client.deleteFile(remotePath);
		}
	}

	/**
	 * Removes a folder recursively.
	 */
	private void recursiveRemoveFolder(FTPClient client, String remotePath)
			throws IOException {
		FTPFile[] files = client.listFiles(remotePath);
		for (FTPFile file : files) {
			if (file.isFile() || file.isSymbolicLink()) {
				client.deleteFile(remotePath + "/" + file.getName());
			}
		}
		for (FTPFile file : files) {
			if (file.isDirectory()) {
				recursiveRemoveFolder(client, remotePath + "/" + file.getName());
				client.removeDirectory(remotePath + "/" + file.getName());
			}
		}
	}
}
